import wx
import win32api
import sys
import os
from settings.config import *
from res.tools.Tools import *


class MainFrame(wx.Frame):
    """程序主窗口类，继承自wx.Frame"""

    text_data = None
    last_index = 0
    current_index = 0
    next_index = 0
    old_text_data_array = [None]*1024

    id_open = wx.NewId()
    id_history = wx.NewId()
    id_quit = wx.NewId()

    id_help = wx.NewId()
    id_about = wx.NewId()

    id_history_one = wx.NewId()
    id_history_two = wx.NewId()
    id_history_three = wx.NewId()

    text_history_one = ""

    def __init__(self, parent):
        """构造函数"""

        wx.Frame.__init__(self, parent, -1, APP_TITLE)
        self.SetBackgroundColour(wx.Colour(240, 240, 240))
        self.SetSize((765, 542))
        self.Center()

        # 以下代码处理图标
        if hasattr(sys, "frozen") and getattr(sys, "frozen") == "windows_exe":
            exeName = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
            icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        else:
            icon = wx.Icon(APP_ICON, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

        # # 以下可以添加各类控件
        # # 设置左侧面板
        # preview = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
        # # 设置面板颜色
        # preview.SetBackgroundColour(wx.Colour(0, 0, 0))

        self.contentText = wx.StaticText(self, wx.ID_ANY, WELCOME_SPEECH, wx.DefaultPosition, wx.DefaultSize, 0)
        self.contentText.Wrap(-1)
        # self.contentText.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVEBORDER))
        # self.contentText.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTIONTEXT))

        layout_main = wx.BoxSizer(wx.VERTICAL)
        layout_main.Add(self.contentText, 1, wx.ALL | wx.EXPAND, 5)

        # sizer_max = wx.BoxSizer()
        # sizer_max.Add(preview, 1, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM | wx.RIGHT, 5)

        self.SetAutoLayout(True)
        self.SetSizer(layout_main)
        self.Layout()

        # 绑定
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        # layout_main.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

        self._CreateMenuBar()
        self._CreateToolBar()
        self._CreateStatusBar()

    # 初始化相关
    def _CreateMenuBar(self):
        """创建菜单栏"""
        self.mb = wx.MenuBar()

        # 文件菜单
        m = wx.Menu()
        m.Append(self.id_open, u"打开文件")
        m.Append(self.id_history, u"历史")
        m.AppendSeparator()
        m.Append(self.id_quit, u"退出")
        self.mb.Append(m, u"文件")

        # 绑定操作
        self.Bind(wx.EVT_MENU, self.OnOpen, id=self.id_open)
        self.Bind(wx.EVT_MENU, self.OnHistory, id=self.id_history)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=self.id_quit)

        # 窗口菜单
        m = wx.Menu()
        m.Append(self.id_help, u"菜单栏")
        m.Append(self.id_about, u"章节")
        m.Append(self.id_about, u"书签")
        self.mb.Append(m, u"窗口")

        # 帮助菜单
        m = wx.Menu()
        m.Append(self.id_help, u"帮助主题")
        m.Append(self.id_about, u"关于...")
        self.mb.Append(m, u"帮助")

        self.Bind(wx.EVT_MENU, self.OnHelp, id=self.id_help)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=self.id_about)

        self.SetMenuBar(self.mb)

    def _CreateToolBar(self):
        """创建工具栏"""
        pass

    def _CreateStatusBar(self):
        """创建状态栏"""
        self.statusbar = self.CreateStatusBar()
        # 将状态栏分割为3个区域,比例为3:2:3
        self.statusbar.SetFieldsCount(3)
        self.statusbar.SetStatusWidths([-3, -2, -3])

        self.statusbar.SetStatusText(u' 状态信息0', 0)
        self.statusbar.SetStatusText(u' Tell:0', 1)
        self.statusbar.SetStatusText(u' 状态信息0', 2)

    # 菜单事件相关
    def OnOpen(self, event):
        """打开文件"""
        # 唤醒路径选择
        file_wildcard = "txt files(*.txt)|*.txt|All files(*.*)|*.*"
        dlg = wx.FileDialog(self, "Open file...", get_desk_p(), style=wx.FD_OPEN, wildcard=file_wildcard)

        if dlg.ShowModal() == wx.ID_OK:
            self.text_data = openFileInit(self, dlg.GetPath())
        dlg.Destroy()

        '''
        TODO 历史记录问题：难以根据读取文件后更改菜单栏中的文本内容
        historyMenu = wx.Menu()
        path = self.text_data.gi_frame.f_locals['path']
        oneItem = wx.MenuItem(historyMenu, self.id_history_one, text=path, kind=wx.ITEM_NORMAL)
        historyMenu.Append(oneItem)
        self.mb.Append(historyMenu, title = '历史')
        '''

        self.NextPage(self)



    def OnHistory(self, event):
        """历史"""
        pass

    def OnQuit(self, event):
        """退出"""
        self.Destroy()

    def OnHelp(self, event):
        """帮助"""
        pass

    def OnAbout(self, event):
        """关于"""
        pass

    # 按键以及按键事件相关
    def OnKeyDown(self, event):
        # 获取按键代码
        kc = event.GetKeyCode()
        print(kc)
        # 314左, 315上, 316右, 317下
        if kc == 316:
            self.NextPage(self)
        if kc == 314:
            self.PreviousPage(self)

    def PreviousPage(self, event):
        """上一页"""
        if self.text_data:
            if self.last_index == 1:
                data_buffer = self.old_text_data_array[0]
                self.contentText.SetLabel(data_buffer)
                return

            self.last_index = self.last_index - 1
            self.current_index = self.current_index - 1
            self.next_index = self.next_index - 1

            data_buffer = self.old_text_data_array[self.last_index - 1]
            if data_buffer is None:
                print(self.old_text_data_array)
                data_buffer = self.old_text_data_array[0]
            self.contentText.SetLabel(data_buffer)

            self.statusbar.SetStatusText("第" + str(self.last_index) + "页")
            self.statusbar.SetFieldsCount(1)

    def NextPage(self, event):
        """下一页"""
        if self.text_data:
            # 数据缓冲区
            self.last_index = self.last_index + 1
            self.current_index = self.last_index + 1
            self.next_index = self.current_index + 1
            try:
                data_buffer = self.old_text_data_array[self.last_index - 1]

                if data_buffer is None :
                    data_buffer = clearTxtBlankLines(next(self.text_data))
                    self.old_text_data_array[self.last_index - 1] = data_buffer

            except :
                data_buffer = clearTxtBlankLines(next(self.text_data))

            self.contentText.SetLabel(data_buffer)

            self.statusbar.SetStatusText("第" + str(self.last_index) + "页")
            self.statusbar.SetFieldsCount(1)

    # 拓展方法相关
    # TODO 为此类创建一个方法，此方法会改变状态栏的tell值，同时将此值存放起来作为书签证明
